<template>
	<view class="page">
		<!-- 顶部渐变背景 -->
		<view class="hero">
			<view class="hero-bg" />
		</view>

		<view class="wrap">
			<!-- 环形进度卡片 -->
			<view class="card ring-card">
				<wd-circle v-model="percent" :stroke-width="40" :size="220" :color="ringColor"
					:layer-color="ringLayerColor" stroke-linecap="round">
					<view class="ring-center">
						<view class="ring-title">今日步数</view>
						<view class="ring-steps">{{ steps }}</view>
						<!-- 仅此处结构微调：加了图标 -->
						<view class="ring-target">
							<wd-icon name="flag" class="target-ico" />
							<text>目标：{{ target }}</text>
						</view>
					</view>
				</wd-circle>
			</view>

			<!-- 功能入口 -->
			<view class="card funcs-card">
				<wd-grid :column="3" :border="false">
					<wd-grid-item @click="goCourses">
						<!-- 新增 @tap.stop 兜底，防止被上层遮挡 -->
						<view class="func-item" @tap.stop="goCourses">
							<image class="func-icon" src="/static/run/course.png" mode="widthFix" />
							<text class="func-text">课程管理</text>
						</view>
					</wd-grid-item>

					<wd-grid-item @click="tip('我的统计')">
						<view class="func-item" @tap.stop="tip('我的统计')">
							<image class="func-icon" src="/static/run/stat.png" mode="widthFix" />
							<text class="func-text">我的统计</text>
						</view>
					</wd-grid-item>

					<wd-grid-item @click="tip('转发分享')">
						<view class="func-item" @tap.stop="tip('转发分享')">
							<image class="func-icon" src="/static/run/share.png" mode="widthFix" />
							<text class="func-text">转发分享</text>
						</view>
					</wd-grid-item>
				</wd-grid>
			</view>

			<!-- 广播 -->
			<view class="notice">
				<wd-notice-bar :scrollable="true" :speed="50" background-color="#e8faf1" color="#2b2b2b">
					<template #prefix>
						<wd-icon class="prefix" name="warn-bold" :size="22" color="#2cc792" />
					</template>
					通知被禁或时段内消息屏蔽可能造成消…
				</wd-notice-bar>

			</view>

			<!-- 今日新闻 -->
			<view class="card news-card">
				<view class="section-title">
					<view class="bar"></view>
					<text>今日新闻</text>
				</view>

				<view v-if="newsLoading" class="news-skeleton">
					<wd-skeleton title :row="3" :row-width="['70%','90%','80%']" />
				</view>

				<view v-else>
					<view v-for="item in news" :key="item.id" class="news-item" @click="openNews(item)">
						<view class="news-title">{{ item.title }}</view>
						<view class="news-meta">
							<text class="source">{{ item.source }}</text>
							<text class="time">{{ item.time }}</text>
						</view>
						<view class="news-summary ellipsis-2">{{ item.summary }}</view>
					</view>

					<view class="more" @click="tip('查看更多')">
						查看更多 <wd-icon name="arrow-right" />
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		watch
	} from 'vue'
	import {
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {
		useAppStore
	} from '@/stores/app'
	import http from '@/http/request'

	/** ========= 顶部环形进度 ========= **/
	const appStore = useAppStore()
	const target = computed(() => {
		const t =
			appStore?.student?.target ??
			appStore?.profile?.targetSteps ??
			appStore?.targetSteps ??
			8000
		return Number(t) || 0
	})

	const steps = ref(0)

	const percent = computed(() => {
		const t = Number(target.value)
		const s = Number(steps.value)
		if (!t || t <= 0) return 0
		return Math.min(100, Math.max(0, Math.round((s / t) * 100)))
	})

	// v-model 需要可写 ref
	const percentVal = ref(0)
	watch(percent, v => {
		percentVal.value = v
	}, {
		immediate: true
	})

	// 颜色
	const ringColor = {
		'0%': '#19C08E',
		'60%': '#12AE7F',
		'100%': '#0A8F69'
	}
	const ringLayerColor = '#D6D9D6'

	// 今日步数
	async function loadTodaySteps() {
		try {
			const res = await http.get('/api/steps/today')
			steps.value = Number(res?.steps ?? 0)
			// 新增：把“真实今日步数”缓存到 Pinia
			const todayKey = new Date().toISOString().slice(0, 10) // 'YYYY-MM-DD'
			const appStore = useAppStore() // 若上面已拿到就复用
			appStore.setTodaySteps(steps.value, todayKey)
		} catch {
			steps.value = 0
		}
	}

	/** ========= 新闻懒加载 ========= **/
	const news = ref([])
	const newsLoading = ref(true) // 首屏骨架
	const newsLoadingMore = ref(false) // 翻页加载状态
	const page = ref(1)
	const pageSize = 10
	const hasMore = ref(true)

	async function fetchNews({
		reset = false
	} = {}) {
		if (reset) {
			news.value = []
			page.value = 1
			hasMore.value = true
			newsLoading.value = true
		}
		if (!hasMore.value || newsLoadingMore.value) return

		if (page.value > 1) newsLoadingMore.value = true

		try {
			const res = await http.get('/api/news/today', {
				page: page.value,
				pageSize
			})
			const list = Array.isArray(res?.list) ? res.list : []
			news.value = news.value.concat(list)

			hasMore.value = typeof res?.hasMore === 'boolean' ?
				res.hasMore :
				list.length >= pageSize

			if (hasMore.value) page.value += 1
		} finally {
			newsLoading.value = false
			newsLoadingMore.value = false
		}
	}

	// 触底继续加载
	onReachBottom(() => {
		if (hasMore.value && !newsLoadingMore.value) fetchNews()
	})

	// 下拉刷新：重置并重新拉第一页
	onPullDownRefresh(async () => {
		await fetchNews({
			reset: true
		})
		uni.stopPullDownRefresh() // ← 这里用全局 API
	})

	/** ========= 跳转/提示 ========= **/
	function goCourses() {
		uni.navigateTo({
			url: '/pages/courses/index'
		})
	}

	function tip(name) {
		if (name === '我的统计')
			// 跳转到分包中的“我的统计”
			uni.navigateTo({
				url: '/my/statistics/statistics'
			});
	}

	function openNews(item) {
		uni.showToast({
			title: item.title,
			icon: 'none'
		})
	}

	/** ========= 首屏 ========= **/
	onMounted(() => {
		loadTodaySteps()
		fetchNews({
			reset: true
		})
	})
</script>

<style lang="scss" scoped>
	$theme-green: #2cc792;
	$page-bg-top: #c4ffd5;
	$page-bg-bottom: #f5f5f5;
	$text-deep: #2b2b2b;

	/* 页面底色：绿色渐变 */
	.page {
		min-height: 100vh;
		background: linear-gradient(to bottom, #c4ffd5 0%, #f5f5f5 25%, #f5f5f5 100%);
	}

	/* 顶部留白更少 */
	.hero {
		height: 140rpx;
		position: relative;

		.hero-bg {
			position: absolute;
			inset: 0;
		}
	}

	/* 内容容器上移，第一卡靠顶 */
	.wrap {
		position: relative;
		top: -120rpx;
		padding: 0 20rpx 24rpx;
	}

	/* 通用卡片（默认半透明磨砂） */
	$card-alpha: .55;

	.card {
		background: rgba(255, 255, 255, $card-alpha);
		border-radius: 24rpx;
		box-shadow: 0 10rpx 24rpx rgba(44, 199, 146, .10);
		padding: 24rpx;
		border: 1rpx solid rgba(255, 255, 255, .7);
		/* #ifdef H5 */
		backdrop-filter: saturate(180%) blur(8px);

		/* #endif */
		+.card {
			margin-top: 20rpx;
		}
	}

	/* ===== 只让 ring-card / funcs-card 完全透明 ===== */
	.ring-card,
	.funcs-card {
		background: transparent !important;
		border: none !important;
		box-shadow: none !important;
	}

	/* 两张卡片贴紧 */
	.ring-card+.funcs-card {
		margin-top: 0 !important;
	}

	/* ====== 点击修复：层级与事件穿透 ====== */
	.funcs-card {
		position: relative;
		z-index: 3;
	}

	/* 让功能卡位于上层，可点 */
	.ring-card {
		position: relative;
		z-index: 1;
	}

	/* 环形卡在下层 */
	.ring-card .ring-center {
		pointer-events: none;
	}

	/* 环中心文本不拦截点击 */

	/* ====== 环形卡：强制真正居中 ====== */
	.ring-card {
		width: 100%;
		padding: 18rpx 0;
		display: flex;
		justify-content: center;
		align-items: center;
		text-align: center;

		:deep(.wd-circle) {
			display: block;
			margin: 0 auto;
		}

		:deep(canvas),
		:deep(.wd-circle__wrapper),
		:deep(.wd-circle__inner) {
			display: block;
			margin: 0 auto;
		}

		.ring-center {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			text-align: center;

			/* —— 放大 + 字间距 —— */
			.ring-title {
				font-size: 32rpx;
				color: #4a4a4a;
				letter-spacing: 2rpx;
				margin-bottom: 14rpx;
			}

			.ring-steps {
				font-size: 88rpx;
				font-weight: 800;
				color: #202020;
				letter-spacing: 4rpx;
				line-height: 1.15;
			}

			.ring-target {
				margin-top: 12rpx;
				font-size: 30rpx;
				color: #6a6a6a;
				display: inline-flex;
				align-items: center;
				gap: 10rpx;
				letter-spacing: 2rpx;
			}

			.target-ico {
				font-size: 30rpx;
				color: $theme-green;
				line-height: 1;
			}
		}
	}

	/* 三宫格卡片：贴紧并稍缩内边距 */
	.funcs-card {
		padding: 8rpx 8rpx 0;
	}

	/* 让功能区每个小块真正完全透明（覆盖 wotdesign 内层） */
	:deep(.wd-grid-item),
	:deep(.wd-grid-item__content) {
		background: transparent !important;
		box-shadow: none !important;
		border: none !important;
	}

	.funcs-card .func-item {
		width: 180rpx;
		height: 180rpx;
		margin: 12rpx auto 18rpx;
		background: transparent !important;
		box-shadow: none !important;
		border: none !important;
		border-radius: 26rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.func-icon {
			width: 72rpx;
			margin-bottom: 12rpx;
		}

		.func-text {
			font-size: 26rpx;
			color: $text-deep;
		}
	}

	/* 广播 */
	.notice {
		margin-top: -30rpx;

		:deep(.prefix) {
			font-size: 18px;
			padding-right: 4px;
			width: 18px;
			height: 18px;
		}
	}

	/* 今日新闻（保持你原样式） */
	.news-card {
		margin-top: 20rpx;

		.section-title {
			display: flex;
			align-items: center;
			font-size: 34rpx;
			font-weight: 600;
			color: $text-deep;
			margin-bottom: 6rpx;

			.bar {
				width: 8rpx;
				height: 32rpx;
				border-radius: 4rpx;
				background: $theme-green;
				margin-right: 12rpx;
			}
		}

		.news-skeleton {
			padding: 8rpx 0;
		}

		.news-item {
			background: rgba(245, 255, 251, .95);
			border: 2rpx solid #e7fbf3;
			border-radius: 18rpx;
			padding: 18rpx;
			margin-top: 14rpx;

			.news-title {
				font-size: 30rpx;
				font-weight: 600;
				color: #2a2a2a;
				line-height: 1.4;
			}

			.news-meta {
				margin-top: 6rpx;
				font-size: 22rpx;
				color: #8b8b8b;
				display: flex;
				gap: 16rpx;
			}

			.news-summary {
				margin-top: 8rpx;
				font-size: 26rpx;
				color: #444;
				line-height: 1.6;
			}
		}

		.more {
			margin-top: 14rpx;
			display: inline-flex;
			align-items: center;
			gap: 8rpx;
			color: $theme-green;
			font-size: 26rpx;
		}
	}

	/* 两行省略 */
	.ellipsis-2 {
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}
</style>